package com.elecbook.util;

import org.apache.logging.log4j.core.appender.FileManager;
import org.junit.Test;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class FileUtil {

    private static final List<String> imageSuffixList = Arrays.asList(".jpg", ".png");

    /**
     * 测试是否为允许的图片结尾
     *
     * @param path
     * @return
     */
    private static boolean isAllowImage(Path path) {
        String pathName = path.toString();
        for (String suffix : imageSuffixList) {
            if (pathName.endsWith(suffix)) {
                return true;
            }
        }
        return false;
    }

    /**
     * String directoryPath = "File/image/"; // 替换为你的目录路径
     *
     * @param directoryPath
     * @return
     */
    static public List<String> getFileList(String directoryPath) {
        // 指定文件夹路径
        Path folderPath = Paths.get(directoryPath);

        // 创建一个列表来存储文件名
        List<String> fileNames = new ArrayList<>();

        try {
            // 使用 Files.walkFileTree 遍历文件夹
            Files.walkFileTree(folderPath, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    // 检查文件是否以 .png 结尾
                    if (isAllowImage(file)) {
                        // 将文件名添加到列表中
                        fileNames.add(file.toString());
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException e) {
            e.printStackTrace(System.err);
        }

        // 打印出所有找到的 .png 文件名
//        fileNames.forEach(System.out::println);
        return fileNames;
    }

    public static void writeListToFile(String filePath, List<String> lines) {
        try {
            // 使用Files.write方法将List中的内容写入到文件中
            Files.write(Paths.get(filePath), lines, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
            System.out.println("文件写入成功！");
        } catch (IOException e) {
            System.err.println("文件写入失败: " + e.getMessage());
        }
    }

    /**
     * 获取mimeType
     * @param path
     * @return
     * @throws IOException
     */
    public static String getMimeType(Path path) throws IOException {
        String mimeType = Files.probeContentType(path);
        return mimeType;
    }
}
